package com.liyuan.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liyuan.entity.HotSection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * GetSessionContext 类用于获取实时热门板块的信息列表。
 * 该类主要通过解析百度热门榜页面的HTML内容，提取出板块标题、内容和来源等信息，并将其封装成HotSection对象的列表返回。
 */
public class GetSessionContext {

    /**
     * 返回包含热门板块信息的字符串列表。
     * 每个字符串代表一个HotSection对象，以对象的toString方法返回的字符串形式表示。
     *
     * @return List<String> 包含热门板块信息的字符串列表。
     */
    public List<String> returnListHostSection() throws IOException, InterruptedException {
        List<String> hotSectionList = new ArrayList<>();
        // 百度热搜
        try {
            // 从指定URL获取HTML文档
            String url = "https://top.baidu.com/board?tab=realtime";
            Document doc = Jsoup.connect(url).get();

            HotSection hotSection = new HotSection();

            // 使用CSS选择器选取需要的信息元素
            String baiduHostDiv = "div.c-single-text-ellipsis,div.hot-desc_1m_jR,div.small_Uvkd3";
            Elements elements = doc.select(baiduHostDiv);

            int cleanNum = 1; // 用于区分解析到的元素位置，以确定信息类型
            int topNum = 1; // 热门板块排名计数器

            for (Element element : elements) {
                ++cleanNum;

                // 根据cleanNum的值，解析并设置板块的标题、内容等属性
                if (cleanNum == 2) {
                    hotSection.setSectionTitle(element.text().replace("\t", " "));
                } else if (cleanNum == 3) {
                    if (element.text().startsWith("查看更多")) {
                        hotSection.setSectionContext("null");
                    } else {
                        hotSection.setSectionContext(element.text().replace("\t", " "));
                    }
                } else {
                    hotSection.setSectionYop(topNum);
                    hotSection.setSectionSource("baidu_hot");
                    hotSection.setCreateTime(System.currentTimeMillis());
                    hotSectionList.add(hotSection.toString());
                    ++topNum;
                    cleanNum = 1; // 重置计数器，准备解析下一个板块信息
                }
            }
        } catch (Exception e) {
            // 异常处理，打印异常信息
            System.out.println(e);
        }
        // 新浪热搜
        String apiUrl = "https://weibo.com/ajax/side/hotSearch";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiUrl))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));

        if (response.statusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.statusCode());
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            Integer xinlangTop = 1;
            JsonNode jsonNode = mapper.readTree(response.body());
            // System.out.println(jsonNode.toPrettyString());
            for (JsonNode itemJson : jsonNode.get("data").get("realtime")) {
                HotSection hotSection = new HotSection();
                hotSection.setSectionYop(xinlangTop++);
                hotSection.setSectionTitle(itemJson.get("word").toPrettyString());
                hotSection.setSectionContext(itemJson.get("word").toPrettyString());
                hotSection.setSectionSource("xinlanghot");
                hotSection.setCreateTime(System.currentTimeMillis());
                hotSectionList.add(hotSection.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // System.out.println(hotSectionList.get(0));
        // 知乎热搜
        String url = "https://www.zhihu.com/billboard";
        Document doc = Jsoup.connect(url).get();
        String zhihuHostDiv = "div.HotList-itemTitle";
        Elements elements = doc.select(zhihuHostDiv);
        int zhihuTop = 1;
        for (Element element : elements) {
            HotSection hotSection = new HotSection();
            hotSection.setSectionYop(zhihuTop++);
            hotSection.setSectionTitle(element.text());
            hotSection.setSectionContext("null");
            hotSection.setSectionSource("zhihuhot");
            hotSection.setCreateTime(System.currentTimeMillis());
            hotSectionList.add(hotSection.toString());
        }
        return hotSectionList;
    }
}
